package com.bestom.videoplay.callback;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothProfile;
import android.content.Intent;
import android.util.Log;

import com.bestom.videoplay.MediaApplication;
import com.bestom.videoplay.beans.CommandBean;
import com.bestom.videoplay.util.DataConversionUtil;
import com.bestom.videoplay.util.ToastUtil;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.logging.Handler;

public class BTGattCallback extends BluetoothGattCallback {


    private String TAG = "BTGattCallback";

    //服务和特征值
    private UUID write_UUID_service;
    private UUID write_UUID_chara;
    private UUID read_UUID_service;
    private UUID read_UUID_chara;
    private UUID notify_UUID_service;
    private UUID notify_UUID_chara;
    private UUID indicate_UUID_service;
    private UUID indicate_UUID_chara;

    /**
     * 断开或连接 状态发生变化时调用
     */
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        super.onConnectionStateChange(gatt, status, newState);
        switch (newState) {
            case BluetoothProfile.STATE_CONNECTING:
                break;
            case BluetoothProfile.STATE_CONNECTED:
                //发现服务
                gatt.discoverServices();
                break;
            case BluetoothProfile.STATE_DISCONNECTING:
                break;
            case BluetoothProfile.STATE_DISCONNECTED:
                Intent intent = new Intent("connect");
                intent.putExtra("status","The Bluetooth connection is disconnected");
                MediaApplication.getApplication().sendBroadcast(intent);
                break;
            default:
        }

    }

    /**
     * 发现设备（真正建立连接）
     */
    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        super.onServicesDiscovered(gatt, status);

        //直到这里才是真正建立了可通信的连接
        initServiceAndChara();
        //订阅通知
        if (notify_UUID_service != null && notify_UUID_chara != null) {
            BluetoothGattCharacteristic characteristic = mBluetoothGatt
                    .getService(notify_UUID_service).getCharacteristic(notify_UUID_chara);
            boolean isEnableNotification = mBluetoothGatt.setCharacteristicNotification(characteristic, true);
            if (isEnableNotification) {
                List<BluetoothGattDescriptor> descriptorList = characteristic.getDescriptors();
                if (descriptorList != null && descriptorList.size() > 0) {
                    for (BluetoothGattDescriptor descriptor : descriptorList) {
                        descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
                        mBluetoothGatt.writeDescriptor(descriptor);
                    }
                }
            }
        }

    }


    /**
     * 读操作的回调
     */
    @Override
    public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicRead(gatt, characteristic, status);
        Log.d(TAG, "onCharacteristicRead()  status=" + status);
    }

    /**
     * 写操作的回调
     */
    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
        super.onCharacteristicWrite(gatt, characteristic, status);

        Log.d(TAG, "onCharacteristicWrite()");

    }

    /**
     * 接收到硬件返回的数据
     */
    @Override
    public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        super.onCharacteristicChanged(gatt, characteristic);

        DataConversionUtil dataConversion = new DataConversionUtil();
        int data = -1;
        byte[] value = characteristic.getValue();
        if (value.length >= 4){
            byte[] bytes = {value[5],value[6],value[7],value[8]};
            data = dataConversion.bytesToInt(bytes, false);
        }

        Intent intent = new Intent("characteristic");
        intent.putExtra("value",String.valueOf(data));
        MediaApplication.getApplication().sendBroadcast(intent);
    }

    private BluetoothGatt mBluetoothGatt;
    private void initServiceAndChara(){
        Intent intent = new Intent("connect");
        String flashingLight = CommandBean.flashingLight.getCommandString();
        mBluetoothGatt = MediaApplication.getApplication().getmBluetoothGatt();
        try {
            List<BluetoothGattService> bluetoothGattServices= mBluetoothGatt.getServices();
            for (BluetoothGattService bluetoothGattService:bluetoothGattServices){
                List<BluetoothGattCharacteristic> characteristics=bluetoothGattService.getCharacteristics();
                for (BluetoothGattCharacteristic characteristic:characteristics){
                    int charaProp = characteristic.getProperties();
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                        read_UUID_chara=characteristic.getUuid();
                        read_UUID_service=bluetoothGattService.getUuid();
                        Log.i(TAG,"read_chara="+read_UUID_chara+"----read_service="+read_UUID_service);
                    }
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
                        write_UUID_chara=characteristic.getUuid();
                        write_UUID_service=bluetoothGattService.getUuid();
                        Log.i(TAG,"write_chara="+write_UUID_chara+"----write_service="+write_UUID_service);
                    }
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) > 0) {
                        write_UUID_chara=characteristic.getUuid();
                        write_UUID_service=bluetoothGattService.getUuid();
                        Log.i(TAG,"write_chara="+write_UUID_chara+"----write_service="+write_UUID_service);

                    }
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                        notify_UUID_chara=characteristic.getUuid();
                        notify_UUID_service=bluetoothGattService.getUuid();
                        Log.i(TAG,"notify_chara="+notify_UUID_chara+"----notify_service="+notify_UUID_service);
                    }
                    if ((charaProp & BluetoothGattCharacteristic.PROPERTY_INDICATE) > 0) {
                        indicate_UUID_chara=characteristic.getUuid();
                        indicate_UUID_service=bluetoothGattService.getUuid();
                        Log.i(TAG,"indicate_chara="+indicate_UUID_chara+"----indicate_service="+indicate_UUID_service);
                    }
                }
            }
            try {
                // 连接成功闪灯5次
                Runtime.getRuntime().exec(flashingLight);
                Thread.sleep(500);
                Runtime.getRuntime().exec(flashingLight);
                Thread.sleep(500);
                Runtime.getRuntime().exec(flashingLight);
                Thread.sleep(500);
                Runtime.getRuntime().exec(flashingLight);
                Thread.sleep(500);
                Runtime.getRuntime().exec(flashingLight);
            } catch (Exception e) {
                e.printStackTrace();
            }
            intent.putExtra("status","Bluetooth connection successful");
        }catch (NullPointerException e){
            intent.putExtra("status","Bluetooth connection fail");
        }
        MediaApplication.getApplication().sendBroadcast(intent);
    }
};

